import { Injectable, LoggerService as NestLoggerService } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as winston from 'winston';
// @ts-ignore
import DailyRotateFile from 'winston-daily-rotate-file';

@Injectable()
export class LoggerService implements NestLoggerService {
  private readonly logger: winston.Logger;

  constructor(private readonly configService: ConfigService) {
    const logLevel = this.configService.get('logging.level', 'info');
    const logFilename = this.configService.get('logging.filename', 'logs/app.log');
    const maxSize = this.configService.get('logging.maxSize', '10m');
    const maxFiles = this.configService.get('logging.maxFiles', '7d');

    // 创建日志目录
    // const logDir = logFilename.substring(0, logFilename.lastIndexOf('/'));
    
    this.logger = winston.createLogger({
      level: logLevel,
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.errors({ stack: true }),
        winston.format.json(),
      ),
      defaultMeta: { service: 'nest-base' },
      transports: [
        // 控制台输出
        new winston.transports.Console({
          format: winston.format.combine(
            winston.format.colorize(),
            winston.format.simple(),
          ),
        }),
        // 文件输出
        // @ts-ignore
        new DailyRotateFile({
          filename: logFilename,
          datePattern: 'YYYY-MM-DD',
          maxSize,
          maxFiles,
          format: winston.format.combine(
            winston.format.timestamp(),
            winston.format.json(),
          ),
        }),
      ],
    });
  }

  log(message: any, context?: string) {
    this.logger.info(message, { context });
  }

  error(message: any, trace?: string, context?: string) {
    this.logger.error(message, { trace, context });
  }

  warn(message: any, context?: string) {
    this.logger.warn(message, { context });
  }

  debug(message: any, context?: string) {
    this.logger.debug(message, { context });
  }

  verbose(message: any, context?: string) {
    this.logger.verbose(message, { context });
  }

  /**
   * 记录HTTP请求日志
   */
  logHttpRequest(
    method: string,
    url: string,
    statusCode: number,
    responseTime: number,
    ip: string,
  ) {
    this.logger.info('HTTP Request', {
      method,
      url,
      statusCode,
      responseTime: `${responseTime}ms`,
      ip,
    });
  }

  /**
   * 记录数据库查询日志
   */
  logDatabaseQuery(query: string, parameters: any[], executionTime: number) {
    this.logger.debug('Database Query', {
      query,
      parameters,
      executionTime: `${executionTime}ms`,
    });
  }

  /**
   * 记录错误日志
   */
  logError(error: Error, context?: string) {
    this.logger.error('Application Error', {
      message: error.message,
      stack: error.stack,
      context,
    });
  }
}